//
//  AppDelegate.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "AppDelegate.h"
//微信
#import "WXApi.h"
#import "WXApiObject.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"

#import "ZWIntroductionViewController.h"

@interface AppDelegate ()<UITabBarControllerDelegate>

@property (nonatomic, strong) ZWIntroductionViewController *introductionView;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [NSThread sleepForTimeInterval:1.0];//设置启动页面时间
    
    //解决图片内存暴走，奔溃
    [[SDImageCache sharedImageCache]setShouldDecompressImages:NO];
    [[SDWebImageDownloader sharedDownloader]setShouldDecompressImages:NO];
    
    self.tabbarIndex = @"";
    theAppdelegate.deviceToken = @"0";
    self.moreModel = nil;
    
    [MTA startWithAppkey:@"I215SPPMNQ6U"];

    //友盟统计
    [self initMobClick];
    //友盟分享
    [UMSocialData setAppKey:UMAppKey];
    //zctx
    [UMSocialWechatHandler setWXAppId:wxAppID appSecret:@"46a92d49504117fecf843ad9ebf3bc01" url:@"http://www.umeng.com/social"];
    
    //设置手机QQ 的AppId，Appkey，和分享URL，需要#import "UMSocialQQHandler.h"
    [UMSocialQQHandler setQQWithAppId:@"1104902860" appKey:@"YAIs8jufwpHQ3VYa" url:@"http://www.umeng.com/social"];
    //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。若在新浪后台设置我们的回调地址，“http://sns.whalecloud.com/sina2/callback”，这里可以传nil ,需要 #import "UMSocialSinaHandler.h"
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    [UMessage startWithAppkey:UMAppKey launchOptions:launchOptions];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
#endif
    [UMessage setLogEnabled:YES];
    
    if ([WXApi registerApp:wxAppID]) {
        NSLog(@"微信支付注册成功！");
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    
    [RegionManager initRegionManager];
    
    [self loadMainView]; // 加载TabBar
    
    [self.window makeKeyAndVisible];
    return YES;
}

/*
 友盟统计
 */
-(void)initMobClick{
    
//    [MobClick setLogEnabled:YES];
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    [MobClick startWithAppkey:UMAppKey reportPolicy:BATCH channelId:nil];
}
/*
 TabBar
 */

- (void)loadMainView{
    
    self.YJTabBar = [[YJTabBarController alloc] init];
    NSArray *coverImageNames =@[@"welcome01", @"welcome02", @"welcome03"];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        self.introductionView = [[ZWIntroductionViewController alloc] initWithCoverImageNames:coverImageNames];
        self.window.rootViewController = self.introductionView;
        __weak AppDelegate *weakSelf = self;
        self.introductionView.didSelectedEnter = ^() {
            [weakSelf.introductionView.view removeFromSuperview];
            weakSelf.introductionView = nil;
            weakSelf.window.rootViewController = weakSelf.YJTabBar;
        };
    }else{
        // → 然后去YJTabBarController中设置子控制器
        self.window.rootViewController = self.YJTabBar;
    }
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigation_bg" ]forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    self.window.backgroundColor = [UIColor whiteColor];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [UMessage registerDeviceToken:deviceToken];
    NSString * strDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                stringByReplacingOccurrencesOfString: @">" withString: @""]
                               stringByReplacingOccurrencesOfString: @" " withString: @""];
    if (strDeviceToken) {
        theAppdelegate.deviceToken = strDeviceToken;
    }
    NSLog(@"deviceToken = %@",theAppdelegate.deviceToken);
    
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //如果注册不成功，打印错误信息，可以在网上找到对应的解决方案
    //如果注册成功，可以删掉这个方法
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UMessage didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        NSLog(@"其他----");
    }
    
    if([sourceApplication isEqualToString:@"com.tencent.xin"])
    {
        return  [WXApi handleOpenURL:url delegate:WeichatManager];
    } else {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            //            NSLog(@"result = %@",resultDic);
//            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayResult" object:nil userInfo:resultDic];
//        }];
    }
    return  YES;
}

-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDWebImageManager sharedManager] cancelAll];
}

//- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
//    int index = (int)tabBarController.selectedIndex;
//    theAppdelegate.tabbarIndex = [NSString stringWithFormat:@"%d",index];
//    [SVProgressHUD dismiss];
//}

@end
